package concurrency.producercunsumer;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Tzachi on 18/10/2014.
 */
public class App {
    private static int producerThreadsSize = 4;
    private static int consumerThreadsSize = 2;

    //TODO: fix with a better implementation
//    private final static ExecutorService producerPool = Executors.newFixedThreadPool(producerThreadsSize);
    private final static ExecutorService producerPool = Tools.newFixedThreadPool(producerThreadsSize);
    private final static ExecutorService consumerPool = Executors.newFixedThreadPool(consumerThreadsSize);

    private final static BlockingQueue<String> workingQueue = new LinkedBlockingQueue<>();

    public static void main(String[] args) throws InterruptedException {
        final AtomicInteger counter = new AtomicInteger(0);
        System.out.println("starting producers");
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    producerPool.submit(new Callable<Object>() {
                        @Override
                        public Object call() throws Exception {
                            workingQueue.add("task #" + counter.getAndIncrement());
                            Thread.sleep(10000);
                            return null;
                        }
                    });
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        System.out.println("starting consumers");
        while (!producerPool.isShutdown()){
            String input = workingQueue.take();
            consumerPool.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    System.out.println(input + " is executed");
                    System.out.println("Queue size: " + workingQueue.size());
                    return null;
                }
            });
//            Thread.sleep(100);
        }

        System.out.println("done");
    }


}
